
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 *
 */

package com.hlkj.pay.util;

import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.hlkj.pay.common.constants.TokenConstant;
import com.hlkj.pay.enums.AuthTokenEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/09/27 18:02
 */
public class JwtTokenUtils {

    /**
     * 生成token
     * 
     * @param key
     * @param tenant
     * @param userId
     * @param appId
     * @param expireTime
     * @param authTokenType
     * @return
     */

    public static String generateToken(String key, Integer sysType,String sn,Long userId, String appId, int expireTime, AuthTokenEnum.AUTH_TOKEN_TYPE authTokenType) {
        long now = System.currentTimeMillis() / TokenConstant.THOUSAND;
        long newTime = now + expireTime;
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(RegisteredPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(RegisteredPayload.EXPIRES_AT, newTime);
        // 生效时间
        payload.put(RegisteredPayload.NOT_BEFORE, now);
        Map<String, String> data = new HashMap<>();
        if (userId != null) {
            data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.USER_ID.getCode(), String.valueOf(userId));
        }
        // data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.TENANT_ID.getCode(), String.valueOf(tenant));
        data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.APP_ID.getCode(), appId);
        data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.AUTH_TOKEN_TYPE.getCode(), authTokenType.getCode().toString());
        data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.SYS_TYPE.getCode(), sysType.toString());
        if(sn==null){
            data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.SN.getCode(), "");
        }else {
            data.put(AuthTokenEnum.AUTH_TOKEN_FIELD.SN.getCode(), sn);
        }
        // 荷载数据
        payload.putAll(data);
        String token = JWTUtil.createToken(payload, key.getBytes());
        return token;
    }
}
